package com.sdc.autohome.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import com.sdc.autohome.bean.ClueBack;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Component
public class ClientRequestData {

    private static final Logger logger = Logger.getLogger(ClientRequestData.class.getName());

//    @Value("${api.url}")
//    private String url;
//
//    @Value("${api.cooperatorId}")
//    private String cooperatorId;
//
//    @Value("${api.user}")
//    private String user;
//
//    @Value("${api.password}")
//    private String password;

    @Value("${api.token_url}")
    private String tokenUrl;

    @Value("${api.advCode}")
    private String advCode;

    @Value("${api.secretKey}")
    private String secretKey;

    @Value("${apitype}")
    private String apiType;


    @Value("${api.file_upload_Url}")
    private String fileUploadUrl;

    @Value("${api.userName}")
    private String userName;

    @Value("${api.source_upload_url}")
    private String sourceUploadUrl;

    @Value("${api.csvFilePath}")
    private String csvFilePath;

    @Autowired
    private RestTemplate restTemplate;

    private String accessToken = null;

    /**
     * 数据源上传
     *
     * @param listClieBack
     * @return
     */
    public JSONObject getDealerData(List<ClueBack> listClieBack) {
        logger.info("发送数据：" + listClieBack.toString());
        logger.info(apiType);
        String fileUploadData = "";
//        if(apiType.equals("prod")){
        accessToken = gettoken(); // 调用获取Token接口，返回token信息
        fileUploadData = getFileUpload(accessToken); // 调用数据源文件上传接口，返回fileKey信息
//        }
        List<String> list = new ArrayList<String>();
        list.add(fileUploadData);

        JSONArray fileKeysArray = new JSONArray();
        fileKeysArray.addAll(list);
        //FormBody.Builder builder = new FormBody.Builder();
        // 设置数据，第一个参数是数据名，第二个参数是数据值
        JSONObject sto = new JSONObject();
        sto.put("advCode", advCode);
        sto.put("fileKeys", fileKeysArray);
        sto.put("name", userName);
//        sto.put("spuInfos", listClieBack.toString());
        RequestBody body = RequestBody.create(sto.toString(), MediaType.get("application/json; charset=utf-8"));
        OkHttpClient client = new OkHttpClient();
        //Request request = new Request.Builder().url(url).post(formBody).build();
        // 构建请求的URL
        // 创建Request对象，设置URL和Authorization头
        Request request = new Request.Builder()
                .url(sourceUploadUrl)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Accept", "application/json")
                .addHeader("token", accessToken)
                .post(body)
                .build();

        logger.info("Content-Type: " + request.headers().get("Content-Type"));
        logger.info("Accept: " + request.headers().get("Accept"));
        logger.info("token: " + request.headers().get("token"));
//        if(apiType.equals("prod")){
        logger.info("请求url：" + sourceUploadUrl + "&access_token=" + accessToken);
//        }
//        else {
//            logger.info("请求url：" + sourceUploadUrl + "&access_token=" + accessToken);
//        }
        JSONObject jsonObject = null;
        String data = "";    //返回的人群数据源 dataSourceId 信息
        try {
            // 执行请求
            Response response = client.newCall(request).execute();

            // 检查响应是否成功
            if (response.isSuccessful()) {
                // 记录响应成功的信息日志
//                logger.info("请求成功: " + response.body());

                jsonObject = JSON.parseObject(response.body().string());
                data = jsonObject.getString("data"); // 返回的 人群数据源 dataSourceId 信息
                String success = jsonObject.getString("success");
                if (!"true".equals(success)) {
                    logger.severe("异常调用getFileUpload接口失败 ");
                } else {
                    logger.info("data：" + data.toString()
                            + "  success: " + jsonObject.getString("success"));
                    logger.info("请求成功：" + jsonObject.toString());
                    System.exit(0);
                }
            } else {
                // 记录响应失败的信息日志
                logger.info("请求失败: " + response);
            }
        } catch (IOException e) {
            // 记录异常的严重日志
            logger.severe("异常: " + e.getMessage());
            e.printStackTrace();
        }

        return jsonObject;

    }

    /**
     * 数据源文件上传
     *
     * @param token
     * @return fileKey信息
     */
    public String getFileUpload(String token) {
        // 构建请求 URL

        String url = fileUploadUrl + "?advCode=" + advCode + "&userInfoType=2";
//        okhttp3.HttpUrl.Builder urlBuilder = okhttp3.HttpUrl.parse(url).newBuilder();
//        urlBuilder.addQueryParameter("advCode",advCode);
//        urlBuilder.addQueryParameter("userInfoType",String.valueOf(2));
//
//        logger.info(apiType);
//
//        Request request = new Request.Builder()
//            .url(url)
//            .addHeader("Content-Type", "multipart/form-data")
//            .addHeader("token", token)
//            .build();
        List<String[]> csvData = readCsvFile(csvFilePath);
        if (csvData != null && !csvData.isEmpty()) {
            // 假设 CSV 文件的第一行是标题，第二行开始是数据
            String[] dataRow = csvData.get(1);  // 选择第二行数据（索引为 1）

            // 从 CSV 中读取变量
            String userId = dataRow[0];  // 假设第一列是 user_id
            String behaviorType = dataRow[1];  // 假设第三列是 behavior_type
            String behaviorTime = dataRow[2];  // 假设第二列是 behavior_time

            File file = new File(csvFilePath);

            if (!file.exists()) {
                logger.info("文件不存在: " + csvFilePath);
            }
            // 构建文件上传请求体
            RequestBody fileBody = RequestBody.create(file, MediaType.parse("application/octet-stream"));
            MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), fileBody);

            // 创建表单字段，使用从 CSV 中读取的变量
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("user_id", userId)  // 添加 "type" 字段
                    .addFormDataPart("behavior_type", behaviorType)  // 添加 "type" 字段
                    .addFormDataPart("behavior_time", behaviorTime)  // 添加 "type" 字段
                    .addPart(filePart)
                    .build();
            logger.info(apiType);
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("Content-Type", "multipart/form-data")
                    .addHeader("token", token)
                    .build();


//            okhttp3.HttpUrl.Builder urlBuilder = okhttp3.HttpUrl.parse(url).newBuilder();
////            if (apiType.equals("prod")) {
////                urlBuilder.addQueryParameter("access_token", token);
////            }
//            // 构建请求的URL
//            Request request = new Request.Builder()
//                    .url(urlBuilder.build().toString())
//                    .addHeader("Content-Type", "multipart/form-data")
//                    .addHeader("Accept", "application/json")
//                    .addHeader("token", token)
//
//                    .build();

            logger.info("Content-Type: " + request.headers().get("Content-Type"));
            logger.info("token: " + request.headers().get("token"));
//            if (apiType.equals("prod")) {
            logger.info("请求url：" + fileUploadUrl + "?advCode=" + advCode + "&userInfoType=2");
//            } else {
//                logger.info("请求url：" + fileUploadUrl + "?advCode=" + advCode + "&userInfoType=2");
//            }
            OkHttpClient client = new OkHttpClient();

            JSONObject jsonObject = null;
            String fileKey = null;
            try {
                // 执行请求
                Response response = client.newCall(request).execute();
//                logger.info(response.body().string());

                // 检查响应是否成功
                if (response.isSuccessful()) {
                    logger.info("jinruchenggong ");
                    jsonObject = JSON.parseObject(response.body().string());
                    logger.info(jsonObject.toString());
                    // 记录响应成功的信息日志
                    //logger.info("请求成功: " + response.body());
                    //{
                    //  "code": 0,
                    //  "success": true,
                    //  "data": "263364556ec9737b42e4cebacc37a90b"
                    //}
//                    jsonObject = JSON.parseObject(response.body().string());
                    fileKey = jsonObject.getString("data");
                    String success = jsonObject.getString("success");
                    logger.info("fileKey：" + fileKey
                            + "  success: " + jsonObject.getString("success"));
                    if (!"true".equals(success)) {
                        logger.severe("异常调用getFileUpload接口失败 ");
                    }
                    logger.info("请求成功：" + jsonObject.toString());
                } else {
                    // 记录响应失败的信息日志
                    logger.info("请求失败: " + response);
                }

                return fileKey;
            } catch (IOException e) {
                // 记录异常的严重日志
                logger.severe("异常: " + e.getMessage());
                e.printStackTrace();
                return "";
            }
        }
        return url;
    }

    /**
     * 获取 TOKEN
     *
     * @return TOKEN
     */
    public String gettoken() {
        String access_token = null;

        JSONObject sto = new JSONObject();
        sto.put("advCode", advCode);        // advCode 必填参数
        sto.put("secretKey", secretKey);    // secretKey 必填参数
//            sto.put("queryType", 2);    // secretKey 必填参数
        RequestBody body = RequestBody.create(sto.toString(), MediaType.get("application/json; charset=utf-8"));
        OkHttpClient client = new OkHttpClient();
        //Request request = new Request.Builder().url(url).post(formBody).build();
        // 构建请求的URL
        Request request = new Request.Builder()
                .url(tokenUrl)
//                    .addHeader("Content-Type", "application/json")
//                    在创建 RequestBody 时，已经通过 MediaType.get("application/json; charset=utf-8")
//                    指定了请求体的 Content-Type 为 application/json 且字符编码为 UTF-8
                .post(body)
                .addHeader("Accept", "application/json")
                .build();
        logger.info(request.toString());
//            {
//                "code": 0,
//                    "success": true,
//                    "data": "d0d4172d74ceff4f205f5f4a77efd952"
//            }
        // 创建 JSONObject
        // 执行请求
        JSONObject jsonObject = null;

        try {
            // 执行请求
            Response response = client.newCall(request).execute();
            logger.info(response.toString());

            // 检查响应是否成功
            if (response.isSuccessful()) {
                // 记录响应成功的信息日志
                //logger.info("请求成功: " + response.body());
                //{
                //  "code": 0,
                //  "success": true,
                //  "data": "263364556ec9737b42e4cebacc37a90b"
                //}
                jsonObject = JSON.parseObject(response.body().string());
                logger.info(jsonObject.toString());
                accessToken = jsonObject.getString("data");
                String success = jsonObject.getString("success");

                if (!"true".equals(success)) {
                    logger.severe("异常调用access_token接口失败 ");
                } else {
                    logger.info("token信息：" + accessToken.toString()
                            + "  success: " + jsonObject.getString("success"));
                    logger.info("请求成功：" + jsonObject.toString());

                    return accessToken;
                }

            } else {
                // 记录响应失败的信息日志
                logger.info("请求失败: " + response);
            }
            return access_token;
        } catch (IOException e) {
            // 记录异常的严重日志
            logger.severe("异常调用access_token接口异常: " + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }

    // 读取 CSV 文件
    private static List<String[]> readCsvFile(String filePath) {
        try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
            return reader.readAll();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (CsvException e) {
            e.printStackTrace();
            return null;
        }
    }
}
